<template>
  <div class="suggest-submit-container-padding">
    <el-form
      ref="ruleFormRef"
      style="max-width: 800px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="课题名称:" prop="name">
        <div class="flex">
          <el-input v-model="ruleForm.name" />
          <el-button type="primary" style="margin-left: 20px" @click="handleAi">
            AI智能查重
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="课题类型:" prop="type">
        <el-select
          v-model="ruleForm.type"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('topic_type')"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业领域:" prop="subjectArea">
        <el-cascader
          v-model="ruleForm.subjectArea"
          :options="majorsTrees"
          :props="optionProps"
          placeholder="请选择"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="研究周期:" prop="researchDate">
        <el-date-picker
          v-model="ruleForm.researchDate"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="flex: 0 0 400px"
        />
      </el-form-item>
      <el-form-item label="预计投入经费:" prop="estimatedBudget">
        <el-input v-model="ruleForm.estimatedBudget" style="width: 300px">
          <template #append>万元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="是否需要外协:" prop="externalCooperationRequired">
        <el-select
          v-model="ruleForm.externalCooperationRequired"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('yes_no')"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="承担单位:" prop="leadingUnitId">
        <el-select
          v-model="ruleForm.leadingUnitId"
          filterable
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in depts"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="协作单位:" prop="collaboratingUnitIds">
        <el-select
          v-model="ruleForm.collaboratingUnitIds"
          multiple
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in depts"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课题负责人:" prop="leader">
        <el-input v-model="ruleForm.leader" style="width: 300px" />
      </el-form-item>
      <el-form-item label="备注:" prop="remarks">
        <el-input v-model="ruleForm.remarks" type="textarea" />
      </el-form-item>
      <el-form-item label="上报单位:" prop="reportingUnitIds">
        <el-select
          v-model="ruleForm.reportingUnitIds"
          multiple
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in depts"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上报人:" prop="reporterIds">
        <el-select v-model="ruleForm.reporterIds" multiple placeholder="请选择">
          <el-option
            v-for="item in users"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="必要性：（含技术现状及对标分析）" prop="necessity">
        <el-input v-model="ruleForm.necessity" type="textarea" />
      </el-form-item>
      <el-form-item label="主要研究内容:" prop="mainResearchContent">
        <el-input v-model="ruleForm.mainResearchContent" type="textarea" />
      </el-form-item>
      <el-form-item
        label="主要技术经济指标:"
        prop="mainTechnoeconomicIndicators"
      >
        <el-input
          v-model="ruleForm.mainTechnoeconomicIndicators"
          type="textarea"
        />
      </el-form-item>
      <el-form-item
        label="前期研究阶段成果（可选项）:"
        prop="preliminaryResearchResults"
      >
        <el-input
          v-model="ruleForm.preliminaryResearchResults"
          type="textarea"
        />
      </el-form-item>
      <el-form-item label="预期成果及达到水平:" prop="anticipatedOutcomes">
        <el-input v-model="ruleForm.anticipatedOutcomes" type="textarea" />
      </el-form-item>
    </el-form>
  </div>
  <CommonFooterBar>
    <el-button :loading="loading" @click="submitForm(ruleFormRef)">
      保存为草稿
    </el-button>
    <el-button
      type="primary"
      :loading="loading"
      @click="submitForm(ruleFormRef, 2)"
    >
      确认提交
    </el-button>
  </CommonFooterBar>
</template>

<script setup>
  import { useDictStore } from '@/store/modules/dict'
  import CommonFooterBar from '@/components/commonFooterBar'
  import {
    createTopic,
    updateTopic,
    getTopicDetail,
  } from '@/api/project/approval/suggest'
  import { getDictTypeTree } from '@/api/system/dict/dict.data'
  import { getAllUser } from '@/api/system/user'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  import { getDeptPage } from '@/api/system/dept/index'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const { closeTabNavigate } = useCloseTabNavigate()

  const $baseMessage = inject('$baseMessage')
  const $XEUtils = inject('$XEUtils')
  const router = useRouter()
  const route = useRoute()
  const dictStore = useDictStore()

  const ruleFormRef = ref()
  let ruleForm = reactive({
    researchDate: [],
    collaboratingUnitIds: [],
    reportingUnitIds: [],
    reporterIds: [],
  })
  const rules = reactive({
    name: [
      {
        required: true,
        message: '请输入课题名称',
      },
    ],
    type: [
      {
        required: true,
        message: '请输入课题类型',
      },
    ],
    subjectArea: [
      {
        required: true,
        message: '请选择专业领域',
        trigger: 'change',
      },
    ],
    researchDate: [
      {
        required: true,
        message: '请选择研究周期',
        trigger: 'change',
      },
    ],
    estimatedBudget: [
      {
        required: true,
        message: '请输入预计投入经费',
      },
    ],
    externalCooperationRequired: [
      {
        required: true,
        message: '请选择是否需要外协',
        trigger: 'change',
      },
    ],
    leadingUnitId: [
      {
        required: true,
        message: '请选择承担单位',
        trigger: 'change',
      },
    ],
    collaboratingUnitIds: [
      {
        required: true,
        message: '请选择协作单位',
        trigger: 'change',
      },
    ],
    leader: [
      {
        required: true,
        message: '请输入课题负责人',
      },
    ],
    remarks: [
      {
        required: false,
        message: '请输入备注',
      },
    ],
    reportingUnitIds: [
      {
        required: true,
        message: '请选择上报单位',
        trigger: 'change',
      },
    ],
    reporterIds: [
      {
        required: true,
        message: '请选择上报人',
        trigger: 'change',
      },
    ],
    necessity: [
      {
        required: true,
        message: '请输入',
      },
    ],
    mainResearchContent: [
      {
        required: true,
        message: '请输入',
      },
    ],
    mainTechnoeconomicIndicators: [
      {
        required: true,
        message: '请输入',
      },
    ],
    preliminaryResearchResults: [
      {
        required: false,
        message: '请输入',
      },
    ],
    anticipatedOutcomes: [
      {
        required: true,
        message: '请输入',
      },
    ],
  })

  const majorsTrees = ref([])
  const optionProps = reactive({
    value: 'value',
    label: 'label',
    emitPath: false, //只传最后一级id
  })

  const users = ref([])
  const depts = ref([])

  const loading = ref(false)

  //获取专业领域数据
  const getMajorsTree = () => {
    getDictTypeTree({ parentId: 149 }).then((res) => {
      if (res.code == 0 || res.code == 200) {
        majorsTrees.value = res.data.children || []
      }
    })
  }

  const getUserList = () => {
    getAllUser().then((res) => {
      if (res.code == 0 || res.code == 200) {
        users.value = res.data || []
      }
    })
  }

  const getDepts = () => {
    getDeptPage().then((res) => {
      if (res.code == 0 || res.code == 200) {
        depts.value = res.data || []
      }
    })
  }

  //ai查重
  const handleAi = () => {
    if (!ruleForm.name) {
      return $baseMessage('请输入课题名称', 'error')
    }
    router.push(`/project/knowledge/ai?keywords=${ruleForm.name}`)
  }

  //初始化数据
  const initFormData = () => {
    if (!route.query.id) return
    getTopicDetail({ id: route.query.id, getType: route.query.getType }).then(
      (res) => {
        if (res.code == 0 || res.code == 200) {
          const data = res.data || {}
          data.researchDate = [
            $XEUtils.toDateString(
              data.researchStartDate,
              'yyyy-MM-dd HH:mm:ss'
            ),
            $XEUtils.toDateString(data.researchEndDate, 'yyyy-MM-dd HH:mm:ss'),
          ]
          data.collaboratingUnitIds = data.collaboratingUnitIds.split(',')
          data.reportingUnitIds = data.reportingUnitIds.split(',')
          data.reporterIds = data.reporterIds.split(',')
          ruleForm = Object.assign(ruleForm, data)
        }
      }
    )
  }

  //表单提交
  const submitForm = async (formEl, type = 1) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        const params = {
          ...ruleForm,
          reporterIds: ruleForm.reporterIds.join(','),
          reportingUnitIds: ruleForm.reportingUnitIds.join(','),
          collaboratingUnitIds: ruleForm.collaboratingUnitIds.join(','),
          researchStartDate: ruleForm.researchDate[0],
          researchEndDate: ruleForm.researchDate[1],
        }
        delete params.researchDate
        loading.value = true
        if (type == 2) {
          const api =
            route.query.id && route.query?.getType == 2
              ? updateTopic
              : createTopic
          if (route.query?.getType == 1) {
            params.draftBoxId = route.query.id
          }
          if (route.query?.getType == 2) {
            params.id = route.query.id
          }
          api(params)
            .then((res) => {
              if (res.code == 0 || res.code == 200) {
                $baseMessage('上报成功')
                closeTabNavigate({ name: 'ProjectApprovalSuggestList' })
              }
            })
            .finally(() => {
              loading.value = false
            })
        } else {
          const formData = {
            id: route.query?.getType == 1 ? route.query.id : '',
            type: 'TOPIC',
            submitJson: JSON.stringify({
              ...params,
              draftBoxId: route.query?.getType == 1 ? route.query.id : '',
            }),
          }

          postDraftBoxCreate(formData)
            .then((res) => {
              if (res.code == 0 || res.code == 200) {
                $baseMessage('保存草稿成功')
                closeTabNavigate({ name: 'ProjectApprovalSuggestList' })
              }
            })
            .finally(() => {
              loading.value = false
            })
        }
      }
    })
  }

  getMajorsTree()
  getUserList()
  getDepts()

  route.query.id && initFormData()
</script>

<style lang="scss" scoped>
  .suggest-submit-container-padding {
    padding-bottom: 80px !important;

    .flex {
      display: flex;
      width: 100%;
    }
  }
</style>
